<template>
  <div class="title">上传报告1</div>
  <t-upload
      v-if="isShowUpload"
      ref="uploadRef"
      v-model="files"
      name="files"
      theme="custom"
      :auto-upload="true"
      :uploadAllFilesInOneRequest="true"
      :showUploadProgress="true"
      :headers="{authorization: token}"
      :data="{assessId: assessId, reportType: '1'}"
      draggable
      :action="url"
      @fail="handleFail"
      @success="handleSuccess"
      @progress="onProgress"
    >
      <template #dragContent="params">
        <div class="show-con" v-if="files && files.length">
          <div v-for="file in files" :key="file.name">
            <div class="show-con__name">{{file.name}} <t-loading :loading="proLoading" size="small" ></t-loading><span class="show-con__progress" v-if="progress>0">{{progress}}% </span></div>
            <div class="show-con__size">文件大小：{{ formatBytes(file.size) }} </div>
            <div class="show-con__date">上传日期：{{ formatTimestamp(file.lastModified) }} </div>
            <div class="show-con__btn" @click.stop="handleCancel(file)" v-show="cancelUp">取消上传</div>
            <!-- <t-button size="small" theme="danger" @click.stop="handleCancel(file)">取消上传</t-button> -->
          </div>
        </div>
        <template v-else>
          <p v-if="params && params.dragActive">释放鼠标</p>
          <div v-else-if="progress < 1" class="up-con">
            <icon name="plus" />
            <div class="up-con__label">拖拽文件到此处或，<span>点击上传</span> </div>
            <div class="up-con__tx">Only pdf, png, jpg can be uploaded, and the size does not exceed 100MB</div>
          </div>
        </template>
        <!-- <t-button v-if="files && files.length" size="small" style="margin-top: 36px">更换文件</t-button> -->
        <!-- <span>数据状态：{{params}}</span> -->
      </template>
    </t-upload>
  <div class="report" v-for="(item, index) in reportFileList" :key="index">
    <div class="report-container">
    <div class="report-container__left">
      <img class="img" src="@/assets/image/report_icon.png" alt="">
      <div class="con">
        <div class="name">{{item.fileName}}</div>
        <div class="size">文件大小: {{item.fileSize}}</div>
        <div class="date">上传日期: {{item.createTime}}</div>
      </div>
    </div>
  </div>
    <img v-if="isShowDelete" @click="delReportCall(item.id)" src="@/assets/image/delete.svg" alt="">
  </div>
  <div class="fixed-container" v-if="approvalProcess <= 3 ">
    <t-space :size="8" class="fixed-container__btn">
        <t-button  theme="default" variant="base" @click="goThreeLast">上一步</t-button>
        <t-button :loading="isLoading"   @click="submitForm()">下一步</t-button>      
      </t-space>
    </div>
 
</template>
<script setup>
import { Icon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from "tdesign-vue-next";
import { getToken, setToken } from '@/utils/auth'
import { approvalReportList, approvalReportOneConfirm, delReport } from '@/api/sjhg/approval'; 
import { uploadMultiFile } from '@/api/sjhg/upload'; 
import _ from 'lodash';
import axios from 'axios';
import { ref } from 'vue';
const props = defineProps({
  assessId: {
    type: Number,
    default: 0
  },
  approvalProcess: {
    type: Number,
    default: 0
  }
})
const cancelUp = ref(false)
const proLoading = ref(false)
const isLoading = ref(false)
const isShowUpload = ref(true)
const isShowDelete = ref(true)
const reportFileList = ref([])
const files = ref([]);
const uploadRef = ref();
const progress = ref(0);
const url = window.lwConfig.services.auth + '/sjhg/approval/assess/report/draft'
console.log('r = ', url)
onMounted(async() => {
  await getReportList();
  console.log('props.approvalProcess==>',props.approvalProcess)
  if (props.approvalProcess != 3) {
    isShowUpload.value = false
    isShowDelete.value = false
  }
})

// 字节
function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// 时间戳
// 使用方法格式化
function formatTimestamp(timestamp) {
  const date = new Date(timestamp);
  return _.join([
    date.getFullYear(),
    _.padStart(date.getMonth() + 1, 2, '0'),
    _.padStart(date.getDate(), 2, '0')
  ], '-') + ' ' + _.join([
    _.padStart(date.getHours(), 2, '0'),
    _.padStart(date.getMinutes(), 2, '0'),
    _.padStart(date.getSeconds(), 2, '0')
  ], ':');
}



//上一步
const emit = defineEmits(["goReportLast","goReportNext"]);
const goThreeLast = ()=>{
  emit('goReportLast')
}

// 取消上传
const handleCancel = (file) => {
  console.log('===============')
  if (uploadRef.value) {
      uploadRef.value.cancelUpload(file);
      console.log('===============',uploadRef.value)
      files.value = files.value.filter(f => f.uid !== file.uid);
  }
  files.value = []
};
const handleSuccess = ({ file }) => {
  // files.value = []
  console.log('response = ', file.response)
  if (file.response.code != 200 || file.response.data.code != 200) {
    MessagePlugin.error(`文件上传失败`);
    files.value=[]
    cancelUp.value = false
    proLoading.value= false 
    progress.value = 0
    return
  }
  if (file.response.code == 200) {
    cancelUp.value = false
    proLoading.value= false 
    progress.value = 0
    if (file.response.data.code == 200) {
      // 调用获取报告列表接口
      getReportList()
    }
  }
  // MessagePlugin.success(`文件 ${file.response.data[0].fileName} 上传成功`);
};
const token = 'Bearer ' + getToken();
console.log('token = ', token)
const handleFail = ({ file }) => {
  MessagePlugin.error(`文件 ${file.name} 上传失败`);
};
const onProgress = ({ percent }) => {
  console.log('进度：', percent);
  progress.value = percent 
  if(percent > 0 ){
    proLoading.value = true
    cancelUp.value = true
  }
  // progress.value = percent;
};
// const handleProgress = ({ percent }) => {
//   console.log('进度：', percent);
//   progress.value = percent;
// };
// const handleProgress = ({ event, file }) => {
//   const percent = Math.round((event.loaded / event.total) * 100);
//   console.log(`文件 ${file.name} 上传进度: ${percent}%`);  // 打印进度信息
// };
// const customRequest = ({ file, onProgress }) => {
//   const formData = new FormData();
//   formData.append('files', file);
//   formData.append("assessId", assessId)
//   formData.append("reportType", "1")
//   saveAssess(submitData)
//       .then((res) => {
//         if (res.code == 200) {
//           MessagePlugin.success('成功');
//           //成功后跳转到下一步
//           emit('goNext',res.data)
//         } else {
//           MessagePlugin.error(res.msg);
//         }
//       })
//       .finally(() => {});
//   } catch (error) {
//     console.error("验证失败:", error);
//   }
//   return axios.post('/upload', formData, {
//     onUploadProgress: (e) => {
//       const percent = Math.round((e.loaded / e.total) * 100); // 避免进度精度问题‌:ml-citation{ref="3" data="citationList"}
//       onProgress({ percent }); // 触发组件进度更新‌:ml-citation{ref="5" data="citationList"}
//     }
//   });
// };

// 进度监听
const handleProgress = (event) => {
  const { file, percent } = event;
  console.log('上传报告进度 = ', Math.round(percent))
};
const upload = () => {
  uploadRef.value.triggerUpload();
};

// 自定义上传请求
const customRequest = async ({ file, onProgress }) => {
  debugger
  const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: (process.env.NODE_ENV === 'development' ? '/api' : window.lwConfig.BASE_API),
    // 超时
    timeout: 100000,
  })
  const formData = new FormData();
  formData.append('files', file.raw);
  formData.append("assessId", props.assessId)
  formData.append("reportType", "1")

  try {
    await service.post('/sjhg/multi/upload', formData, {
      headers: {'files': file, 'authorization': token, 'Content-Type': 'multipart/form-data' },
      onUploadProgress: (e) => {
        onProgress({ event: e, file });  // 主动触发进度回调‌:ml-citation{ref="2,3" data="citationList"}
      }
    });
  } catch (error) {
    console.error('上传失败:', error);
  }
};

const getReportList = async () => {
  var params = {}
  params.assessId = props.assessId
  params.reportType = 1
  approvalReportList(params)
      .then((res) => {
        console.log('出具报告返回 = ', res)
        if (res.code == 200) {
          reportFileList.value = res.data || []
          console.log('reportFileList.value = ', reportFileList.value)
        }
      }).finally(() => {
      });
}

// 上传出具报告
const submitForm = () => {
  var params = {}
  params.assessId = props.assessId
  params.reportType = 1
  isLoading.value = true
  approvalReportOneConfirm(params)
      .then((res) => {
        console.log('出具报告确认返回 = ', res)
        if (res.code == 200) {
          emit('goReportNext')
        }
      }).finally(() => {
        isLoading.value = false
      });
}

const delReportCall = (reportId) => {
  var params = {}
  params.reportId = reportId
  delReport(params)
      .then((res) => {
        console.log('删除报告返回 = ', res)
        if (res.code == 200) {

          files.value = []
          MessagePlugin.success(res.msg)
          getReportList()
        } else {
          MessagePlugin.warning(res.msg)
        }
      }).finally(() => {

      });
}

</script>
<style lang="scss" scoped>
.fixed-container{
  height: 72px;
  position: fixed;
  bottom:0;
  right: 0;
  left: 196px;
  border-bottom-left-radius: 16px;
  border-bottom-right-radius:16px;
  background: #FFF;
  box-shadow: 1px 0px 1px 0px rgba(0, 0, 0, 0.25);
  display: flex;
  justify-content: flex-end;
  align-items: center;
  &__btn{
    margin-right: 20px;
  }
}
.show-con{
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;

  :deep(.t-upload__dragger-center){
    justify-content: flex-start;
  }
  :deep(.t-upload__dragger){
    border: 1px dashed #DCDCDC;
    background: #FFFF;
  }
  &__name{
    display: flex;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.90);
    line-height: 22px;
  }
  &__progress{
    font-size: 14px;
    font-weight: 400;
    line-height: 22px;
    color:#0052D9;
  }
  &__size{
    font-size: 12px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.40);
    line-height: 20px;
    margin-top: 8px;
  }
  &__date{
    font-size: 12px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.40);
    line-height: 20px;
  }
  &__btn{
    cursor: pointer;
    font-size: 14px;
    font-weight: 400;
    line-height: 22px;
    color:#0052D9;
    margin-top: 20px;
    z-index: 9999;
  }
}
.up-con{
  display: flex;
  flex-direction: column;
  align-items: center;
  &__label{
    margin-top: 24px;
    font-size: 14px;
    color: #1D2129;
  }
  span{
    color: #165DFF;
  }
  &__tx{
    color:#86909C;
    font-size: 12px;
    line-height: 20px;
  }
  :deep(.t-upload__dragger){
    border-radius: 4px;
    border: 1px solid #DCDCDC;
    background: #F2F3F5;
    cursor: pointer;
    &:hover{
      background: #C9CDD4;
    }
  }
}
:deep(.t-upload__dragger){
    width: 100%;
    height: 184px;
}
.report{
  display: flex;
  align-items: center;

  img{
    width: 24px;
    height: 24px;
    margin-left: 12px;
  }
}
.report-container{
  width: 619px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #DCDCDC;
  border-radius: 4px;
  margin-top: 16px;
  .img{
    width: 90px;
    height: 90px;
  }
  .name{
    font-size: 16px;
    color:#000000E5;
    margin-top: 4px;
  }
  .size{
    margin-top: 12px;
    line-height: 22px;
    color:#00000066;
    font-weight: 400;
    font-size: 14px;
  }
  .date{
    line-height: 22px;
    color:#00000066;
    font-weight: 400;
    font-size: 14px;
    margin-top: 2px;
  }
  .con{
    margin-left: 16px;

  }
  &__left{
    display: flex;
    
  }

}
.title{
  font-size: 18px;
  color: #252931;
  margin-top: 8px;
  margin-bottom: 17px;
}
:deep(.t-upload__dragger-progress) {
  width: 100%;
  margin-left: 42%;
}
</style>